<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>unused</title>
  </head>
  <body>
    <script id="configVals" onload="runWhenAllowed()"></script>
    <script>
      var pluginHost;
      var mapDocument = null;

      function runWhenAllowed() {
        var originalZoom = -1;
        var originalCenterAircraft = -1;
        var originalAutoRefresh = -1;
        
        var enabled = true;
        var firstTime = true;
        var lastPower = -10;
        var timeout = null;
        var running = true;
        
        runWhenAllowed.stop = function () {
          clearTimeout(timeout);
          running = false;
          restoreValuesPerhapsOverridden();
        };

        function restoreValuesPerhapsOverridden() {
          if(!originalCenterAircraft && runWhenAllowed.centerToggle.checked) {
            runWhenAllowed.centerToggle.click();
          }
          if(!originalAutoRefresh && runWhenAllowed.mapToggle.checked) {
            runWhenAllowed.mapToggle.click();
          }
          originalZoom > -1 ? fetch("/mapimage?format=jpg&quality=1&width=1&height=1&distance=" + Math.pow(2, originalZoom) + "&session&cmd=" + Math.random()) : !1;
          runWhenAllowed.docMap?.querySelector('[onclick="refreshMap()"]').click();
        }

        function autozoom() {
          fetch("/api/sim/info").then(function(response) {
            if(running && enabled) {
              return response.json();
            } else {
              return Promise.reject();
            }
          }).then(function(json) {
            if(json.active) {
              var speed = ~~json.ground_speed;
              var alt = json.altitude_above_ground;
              var i=0;
              while(i < zoomKnots.length && speed >= zoomKnots[i]) {
                i++;
              }
              var speedIndex = i - 1;
              i=0;
              while(i < zoomAltsAbvGrd.length && alt >= zoomAltsAbvGrd[i]) {
                i++;
              }
              var newPower = zoomPowerForKnots[speedIndex] + zoomPowerAddForAltsPerKnot["" + zoomKnots[speedIndex]][i - 1];
              if(newPower !== lastPower) {
                lastPower = newPower;
                var wasChecked = false;
                if(runWhenAllowed.mapToggle.checked) {
                  wasChecked = true;
                  runWhenAllowed.mapToggle.checked = false;
                  runWhenAllowed.docMap.defaultView.checkRefresh();   // temporarily disable to prevent our fetch getting cancelled by refresh, but don't give away to user
                }
                // the webserver saves the view state, update that state, thus only request an 1x1 image for performance reason
                fetch("/mapimage?format=jpg&quality=1&width=1&height=1&distance=" + Math.pow(2, newPower) + "&session&cmd=" + Math.random()).then(function() {
                  if(wasChecked) {
                    runWhenAllowed.mapToggle.checked = true;
                    runWhenAllowed.docMap.defaultView.checkRefresh();
                  }
                  timeout = setTimeout(autozoom, zoomWaitForKnots[speedIndex] * 1000);
                });
              } else {
                timeout = setTimeout(autozoom, zoomWaitForKnots[speedIndex] * 1000);
              }
            } else {
              timeout = setTimeout(autozoom, 10000);
            }
          }).catch(function(e){
            console?.error("Error! Are the configuration values consistent?");
            console?.log(e);
          });
        }

        function saveValuesToGetOverridden() {
          fetch("/api/ui/info").then(function(response) {
            if(response.ok) {
              return response.json();
            } else {
              originalZoom = -1;
            }
          }).then(function(json) {
            originalZoom = Math.log(json.distance_web) / Math.log(2);
          });
          originalCenterAircraft = runWhenAllowed.centerToggle.checked;
          originalAutoRefresh = runWhenAllowed.mapToggle.checked;
        }

        function checkIframeSrc() {
          try {
            enabled = runWhenAllowed.docMap.defaultView.location.href.endsWith("/html/2021-a/map.html");
          } catch(e) {
            parent.postMessage({"throw": "map not found"}, "*");
            return;
          }
          if(enabled) {
            if(firstTime) {
              firstTime = false;
              saveValuesToGetOverridden();
              if(!originalCenterAircraft) {
                runWhenAllowed.centerToggle.click();
              }
              if(!originalAutoRefresh) {
                runWhenAllowed.mapToggle.click();
              }
            }
            autozoom();
          } else {
            clearTimeout(timeout);
          }
        }

        checkIframeSrc();
      }
      
      
      function stop() {
        runWhenAllowed.stop?.();
      }
      
      function start() {
        if(mapDocument !== null) {
          if(mapsVersion !== 1 && !confirm("New map version running possibly unsupported.\n\nDo you like to let run this plugin anyway?")) {
            return pluginHost.postMessage({"throw": "aborted by user"}, "*");
          }
          if(sessionStorage.getItem("autozoomRead") !== "true") {
            if(confirm(
              "This plugin attempts to set the zoom level of the\n" +
              "map according to the level it deems most appro-\n" +
              "priate for the circumstances you are in.\n\n" +
              "It enables \"auto refresh\" and \"center is Aircraft\" and\n" +
              "restores the value they are in now when you disable it.\n\n" +
              "You can change the defining values it operates on\n" +
              "inside the file \"configurationValues.js\" inside the\n" +
              "folder \"web\\plugins\\autozoom\" in the folder of Little Navmap.\n\n" +
              "If you continue, this message is dismissed for this session."
              )) {
              sessionStorage.setItem("autozoomRead", "true");
            } else {
              parent.postMessage({"throw": "cancelled by user"}, "*");
            }
          }

          runWhenAllowed.docMap = mapDocument;

          runWhenAllowed.mapToggle = runWhenAllowed.docMap.querySelector("#refreshMapToggle");
          runWhenAllowed.centerToggle = runWhenAllowed.docMap.querySelector("#refreshWithAircraft");
          
          document.getElementById("configVals").src = "configurationValues.js";
        } else {
          pluginHost.postMessage({"throw": "neccessary access not given"}, "*");
        }
      }
      
      onmessage = event => {
        let message = event.data.pluginParent;
        if(message) {
          switch(message.cause) {
            case "cleanup":
              return stop();
            case "commence":
              pluginHost = event.source;
              return start();
            default:
          }
        }
      };
      
      function setMapDocument(iframeDocument, mapVersion) {
        mapDocument = iframeDocument;
        mapsVersion = mapVersion;
      }
    </script>
  </body>
</html>